package pl.org.lutra.planner.gui.table;

import java.awt.Component;
import java.text.Format;

import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JTable;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableCellRenderer;

public class PaddingTableCellRenderer extends DefaultTableCellRenderer {
    private static final long serialVersionUID = 5242218890713761593L;
    
    private static final Border PADDING_BORDER = BorderFactory.createEmptyBorder(1, 1, 1, 11);
    private static final Border INTERNAL_PADDING_BORDER = BorderFactory.createEmptyBorder(0, 0, 0, 10);
    
    private Format format;
    
    public PaddingTableCellRenderer(Format format) {
        this.format = format;
        
        setHorizontalAlignment(SwingConstants.RIGHT);
    }
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
            boolean hasFocus, int row, int column) {
        JComponent component =
                (JComponent) super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row,
                        column);
        
        Border border = component.getBorder();
        if (border != null) {
            component.setBorder(BorderFactory.createCompoundBorder(border, INTERNAL_PADDING_BORDER));
        } else {
            component.setBorder(PADDING_BORDER);
        }
        
        return component;
    }
    
    @Override
    protected void setValue(Object value) {
        setText(format.format(value));
    }
    
}
